import db from './db.js';

document.addEventListener('DOMContentLoaded', async () => {
  const searchInput = document.getElementById('searchInput');
  const sortSelect = document.getElementById('sortSelect');
  const selectAllBtn = document.getElementById('selectAllBtn');
  const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
  const mergeSelectedBtn = document.getElementById('mergeSelectedBtn');
  const exportSelectedBtn = document.getElementById('exportSelectedBtn');
  const importFileInput = document.getElementById('importFileInput');
  const importBtn = document.createElement('button');
  importBtn.className = 'primary-btn';
  importBtn.textContent = '导入';
  importBtn.onclick = () => importFileInput.click();
  exportSelectedBtn.parentNode.insertBefore(importBtn, importFileInput);
  let selectedGroups = new Set();

  // 加载并显示标签组
  async function loadTabGroups() {
    try {
      return await db.getAllTabGroups();
    } catch (error) {
      console.error('加载标签组时出错：', error);
      return [];
    }
  }

  // 搜索和排序标签组
  function filterAndSortTabGroups(tabGroups, searchText, sortType) {
    let filtered = tabGroups;

    // 收藏过滤
    const favoriteFilter = document.getElementById('favoriteFilter');
    if (favoriteFilter && favoriteFilter.checked) {
      filtered = filtered.filter((group) => group.favorite);
    }

    // 搜索过滤
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      filtered = filtered.filter((group) => {
        const matchInTitle = group.name.toLowerCase().includes(lowerSearchText);
        const matchInTabs = group.tabs.some(
          (tab) =>
            tab.title.toLowerCase().includes(lowerSearchText) ||
            tab.url.toLowerCase().includes(lowerSearchText),
        );
        return matchInTitle || matchInTabs;
      });
    }

    // 排序
    return filtered.sort((a, b) => {
      switch (sortType) {
        case 'time-desc':
          return b.id - a.id;
        case 'time-asc':
          return a.id - b.id;
        case 'name-asc':
          return a.name.localeCompare(b.name);
        case 'name-desc':
          return b.name.localeCompare(a.name);
        case 'tabs-desc':
          return b.tabs.length - a.tabs.length;
        case 'tabs-asc':
          return a.tabs.length - b.tabs.length;
        default:
          return 0;
      }
    });
  }

  // 渲染标签组列表
  function renderTabGroups(groups) {
    const tabGroupsContainer = document.getElementById('tabGroups');
    tabGroupsContainer.innerHTML = groups
      .map(
        (group) => `
        <div class="tab-group ${
          selectedGroups.has(group.id) ? 'selected' : ''
        }" data-group-id="${group.id}">
          <div class="tab-group-header">
            <div>
              <h3 class="tab-group-title">${group.name}</h3>
              <span class="tab-count">${group.tabs.length} 个标签页</span>
            </div>
            <div class="tab-group-actions">
              <button class="favorite-btn icon-btn ${
                group.favorite ? 'active' : ''
              }" data-group-id="${group.id}">
                <img src="images/icons/star.svg" alt="收藏" class="icon">
              </button>
              <button class="restore-group-btn primary-btn" data-group-id="${
                group.id
              }">恢复</button>
              <button class="delete-group-btn danger-btn" data-group-id="${
                group.id
              }">删除</button>
            </div>
          </div>
          <div class="tab-list">
            ${group.tabs
              .map(
                (tab, index) => `
              <div class="tab-item">
                <img src="${
                  tab.favIconUrl || 'images/icon16.png'
                }" alt="" style="width: 16px; height: 16px;">
                <span class="tab-title">${tab.title}</span>
                <div class="tab-actions">
                  <button class="open-tab-btn icon-btn" data-group-id="${
                    group.id
                  }" data-tab-index="${index}">
                    <img src="images/icons/visit.svg" alt="打开" class="icon">
                  </button>
                  <button class="delete-tab-btn icon-btn danger" data-group-id="${
                    group.id
                  }" data-tab-index="${index}">
                    <img src="images/icons/trash.svg" alt="删除" class="icon">
                  </button>
                </div>
              </div>
            `,
              )
              .join('')}
          </div>
        </div>
      `,
      )
      .join('');
  }

  // 更新标签组显示
  async function updateTabGroups() {
    const groups = await loadTabGroups();
    const filteredAndSorted = filterAndSortTabGroups(
      groups,
      searchInput.value,
      sortSelect.value,
    );
    renderTabGroups(filteredAndSorted);
  }

  // 搜索和排序事件处理
  searchInput.addEventListener('input', updateTabGroups);
  sortSelect.addEventListener('change', updateTabGroups);
  document
    .getElementById('favoriteFilter')
    .addEventListener('change', updateTabGroups);

  // 批量操作事件处理
  selectAllBtn.addEventListener('click', async () => {
    const groups = await loadTabGroups();
    if (selectedGroups.size === groups.length) {
      selectedGroups.clear();
    } else {
      selectedGroups = new Set(groups.map((g) => g.id));
    }
    updateTabGroups();
  });

  deleteSelectedBtn.addEventListener('click', async () => {
    if (selectedGroups.size === 0) return;
    if (!confirm(`确定要删除选中的 ${selectedGroups.size} 个标签组吗？`))
      return;

    const tabGroups = await loadTabGroups();
    const updatedGroups = tabGroups.filter((g) => !selectedGroups.has(g.id));
    for (const group of tabGroups) {
      if (selectedGroups.has(group.id)) {
        await db.deleteTabGroup(group.id);
      }
    }
    selectedGroups.clear();
    updateTabGroups();
  });

  mergeSelectedBtn.addEventListener('click', async () => {
    if (selectedGroups.size < 2) {
      alert('请至少选择两个标签组进行合并');
      return;
    }

    const tabGroups = await loadTabGroups();
    const selectedGroupsData = tabGroups.filter((g) =>
      selectedGroups.has(g.id),
    );

    // 创建新的合并标签组
    const mergedGroup = {
      id: Date.now(),
      name: `合并的标签组 (${new Date().toLocaleString()})`,
      tabs: selectedGroupsData.flatMap((g) => g.tabs),
      favorite: false,
    };

    // 更新存储
    await db.addTabGroup(mergedGroup);
    for (const group of selectedGroupsData) {
      await db.deleteTabGroup(group.id);
    }
    selectedGroups.clear();
    updateTabGroups();
  });

  exportSelectedBtn.addEventListener('click', async () => {
    if (selectedGroups.size === 0) {
      alert('请至少选择一个标签组进行导出');
      return;
    }

    const tabGroups = await loadTabGroups();
    const selectedGroupsData = tabGroups.filter((g) =>
      selectedGroups.has(g.id),
    );

    const blob = new Blob([JSON.stringify(selectedGroupsData, null, 2)], {
      type: 'application/json',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `标签组导出_${new Date().toLocaleString()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  });

  importFileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const importedGroups = JSON.parse(e.target.result);
        if (!Array.isArray(importedGroups)) {
          throw new Error('导入的文件格式不正确');
        }

        await db.importTabGroups(importedGroups);
        updateTabGroups();
        alert('导入成功');
      } catch (error) {
        console.error('导入标签组时出错：', error);
        alert('导入失败：' + error.message);
      }
      event.target.value = '';
    };
    reader.readAsText(file);
  });

  // 标签组点击事件处理
  document.getElementById('tabGroups').addEventListener('click', async (e) => {
    const target = e.target;
    const button = target.closest('button');
    if (!button) {
      const tabGroup = target.closest('.tab-group');
      if (tabGroup) {
        const groupId = Number(tabGroup.dataset.groupId);
        if (selectedGroups.has(groupId)) {
          selectedGroups.delete(groupId);
        } else {
          selectedGroups.add(groupId);
        }
        updateTabGroups();
      }
      return;
    }

    if (button.matches('.restore-group-btn')) {
      const groupId = Number(button.dataset.groupId);
      await restoreTabGroup(groupId);
    } else if (button.matches('.delete-group-btn')) {
      const groupId = Number(button.dataset.groupId);
      await deleteTabGroup(groupId);
    } else if (button.matches('.open-tab-btn')) {
      const groupId = Number(button.closest('.tab-group').dataset.groupId);
      const tabIndex = parseInt(button.dataset.tabIndex);
      await openSingleTab(groupId, tabIndex);
    } else if (button.matches('.delete-tab-btn')) {
      const groupId = Number(button.closest('.tab-group').dataset.groupId);
      const tabIndex = parseInt(button.dataset.tabIndex);
      await deleteTabFromGroup(groupId, tabIndex);
    } else if (button.matches('.favorite-btn')) {
      const groupId = Number(button.closest('.tab-group').dataset.groupId);
      await toggleFavorite(groupId);
    }
  });

  // 恢复标签组
  async function restoreTabGroup(groupId) {
    try {
      const tabGroups = await loadTabGroups();
      const group = tabGroups.find((g) => g.id === groupId);
      if (!group) return;

      // 创建新窗口并打开所有标签页
      const window = await chrome.windows.create();
      await Promise.all(
        group.tabs.map((tab) =>
          chrome.tabs.create({
            windowId: window.id,
            url: tab.url,
          }),
        ),
      );

      // 关闭新窗口创建时的空白标签页
      const tabs = await chrome.tabs.query({ windowId: window.id });
      if (tabs.length > 0) {
        await chrome.tabs.remove(tabs[0].id);
      }
    } catch (error) {
      console.error('恢复标签组时出错：', error);
    }
  }

  // 删除标签组
  async function deleteTabGroup(groupId) {
    try {
      if (!confirm('确定要删除这个标签组吗？')) return;
      await db.deleteTabGroup(groupId);
      selectedGroups.delete(groupId);
      await updateTabGroups();
    } catch (error) {
      console.error('删除标签组时出错：', error);
      alert('删除标签组失败：' + error.message);
    }
  }

  // 打开单个标签页
  async function openSingleTab(groupId, tabIndex) {
    try {
      const tabGroups = await loadTabGroups();
      const group = tabGroups.find((g) => g.id === groupId);
      if (!group || !group.tabs[tabIndex]) return;

      // 检查是否已存在相同URL的标签页
      const existingTabs = await chrome.tabs.query({});
      const existingTab = existingTabs.find(
        (tab) => tab.url === group.tabs[tabIndex].url,
      );

      if (existingTab) {
        // 如果存在相同URL的标签页，则激活该标签页
        await chrome.tabs.update(existingTab.id, { active: true });
        await chrome.windows.update(existingTab.windowId, { focused: true });
      } else {
        // 如果不存在，则创建新标签页
        await chrome.tabs.create({
          url: group.tabs[tabIndex].url,
        });
      }
    } catch (error) {
      console.error('打开标签页时出错：', error);
      alert('打开标签页失败：' + error.message);
    }
  }

  // 从标签组中删除标签页
  async function deleteTabFromGroup(groupId, tabIndex) {
    try {
      const tabGroups = await loadTabGroups();
      const group = tabGroups.find((g) => g.id === groupId);
      if (!group) return;

      group.tabs.splice(tabIndex, 1);
      if (group.tabs.length === 0) {
        await db.deleteTabGroup(groupId);
      } else {
        await db.updateTabGroup(group);
      }
      updateTabGroups();
    } catch (error) {
      console.error('删除标签页时出错：', error);
    }
  }

  // 切换收藏状态
  async function toggleFavorite(groupId) {
    try {
      const tabGroups = await loadTabGroups();
      const group = tabGroups.find((g) => g.id === groupId);
      if (!group) return;

      group.favorite = !group.favorite;
      await db.updateTabGroup(group);
      updateTabGroups();
    } catch (error) {
      console.error('切换收藏状态时出错：', error);
    }
  }
  // 初始化
  updateTabGroups();
});
